package com.passer.toolbox.common.file.filter;

import com.passer.toolbox.common.file.constant.enums.FileType;

import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexFilenameFilter implements FilenameFilter {
    private final String regex;
    private final FileType fileType;

    public RegexFilenameFilter(String regex, FileType fileType) {
        this.regex = regex;
        this.fileType = fileType;
    }

    @Override
    public boolean accept(File dir, String name) {
        File file = new File(dir, name);
        if ((this.fileType == FileType.File && file.isDirectory()) || (this.fileType == FileType.Folder && file.isFile())) {
            return true;
        }
        Pattern compile = Pattern.compile(regex);
        Matcher matcher = compile.matcher(name);
        return matcher.find();
    }
}
